package com.authine.cloudpivot.web.api.secondopen.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.authine.cloudpivot.web.api.config.DingDingConfig;
import com.authine.cloudpivot.web.api.config.HxConfig;
import com.authine.cloudpivot.web.api.secondopen.dao.EjkmjcxxwhMapper;
import com.authine.cloudpivot.web.api.secondopen.dao.Ie6s6CurrencyMaintainMapper;
import com.authine.cloudpivot.web.api.secondopen.dao.Ie6s6KjdwxxMapper;
import com.authine.cloudpivot.web.api.secondopen.dao.Ie6s6KmjcxxMapper;
import com.authine.cloudpivot.web.api.secondopen.dao.Ie6s6cbzxwhjcxxMapper;
import com.authine.cloudpivot.web.api.secondopen.dao.MonthlybudgetadjustrecordMapper;
import com.authine.cloudpivot.web.api.secondopen.dao.QnyssqMapper;
import com.authine.cloudpivot.web.api.secondopen.dao.SyncDDMapper;
import com.authine.cloudpivot.web.api.secondopen.dao.YjkmjcxxwhMapper;
import com.authine.cloudpivot.web.api.secondopen.domain.Account;
import com.authine.cloudpivot.web.api.secondopen.domain.Dept;
import com.authine.cloudpivot.web.api.secondopen.domain.DingDingUser;
import com.authine.cloudpivot.web.api.secondopen.domain.Ie6s6CurrencyMaintain;
import com.authine.cloudpivot.web.api.secondopen.domain.Ie6s6Kjdwxx;
import com.authine.cloudpivot.web.api.secondopen.domain.Ie6s6Kmjcxx;
import com.authine.cloudpivot.web.api.secondopen.domain.Ie6s6cbzxwhjcxx;
import com.authine.cloudpivot.web.api.secondopen.domain.Monthlybudgetadjustrecord;
import com.authine.cloudpivot.web.api.secondopen.domain.Qnyssq;
import com.authine.cloudpivot.web.api.secondopen.domain.SubAccount;
import com.authine.cloudpivot.web.api.secondopen.service.SyncService;
import com.authine.cloudpivot.web.api.secondopen.utils.DingDingUtil;
import com.authine.cloudpivot.web.api.secondopen.utils.HttpRestUtil;
import com.authine.cloudpivot.web.api.utils.StringUtils;
import com.dingtalk.api.response.OapiV2UserGetResponse;
import com.dingtalk.api.response.OapiV2UserGetbymobileResponse;
import com.taobao.api.ApiException;
import io.jsonwebtoken.lang.Collections;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.stream.IntStream;


@Service
public class SyncServiceImpl implements SyncService {
    private static final Logger log = LoggerFactory.getLogger(SyncServiceImpl.class);

    @Autowired(required=true)
    private QnyssqMapper qnyssqMapper;

    @Autowired(required=true)
    private MonthlybudgetadjustrecordMapper monthlybudgetadjustrecordMapper;

    @Autowired
    private Ie6s6KmjcxxMapper ie6s6KmjcxxMapper;

    @Autowired
    private Ie6s6cbzxwhjcxxMapper ie6s6cbzxwhjcxxMapper;

    @Autowired
    private HxConfig hxConfig;

    @Autowired
    private Ie6s6CurrencyMaintainMapper ie6s6CurrencyMaintainMapper;

    @Autowired
    private YjkmjcxxwhMapper yjkmjcxxwhMapper;

    @Autowired
    private EjkmjcxxwhMapper ejkmjcxxwhMapper;

    @Autowired
    private Ie6s6KjdwxxMapper ie6s6KjdwxxMapper;

    @Autowired
    private DingDingConfig ddconfig;

    @Autowired
    private SyncDDMapper syncddmapper;


    @Override
    @Transactional
    public void syncAnnualBudgetInService() {
        //查询未同步的全年预算信息
        List<Qnyssq> qnyssqs=qnyssqMapper.selectQnyssqList();
        log.info("---------------本次同步全年预算额度数量为"+qnyssqs.size()+"条---------------");
        if(!Collections.isEmpty(qnyssqs)){
            List<String> ids=new ArrayList<>();
            for (Qnyssq qnyssq : qnyssqs) {
                if(qnyssq!=null){
                    if(StringUtils.isBlank(qnyssq.getNf()) || StringUtils.isBlank(qnyssq.getOneaccountcode()) || StringUtils.isBlank(qnyssq.getTwoaccountcode()) ||
                            StringUtils.isBlank(qnyssq.getYscbzx()) || StringUtils.isBlank(qnyssq.getFygsbm())){
                        log.info("数据不完整，跳过，数据为:"+JSON.toJSONString(qnyssq));
                        continue;
                    }
                    Monthlybudgetadjustrecord monthlybudgetadjustrecord=this.copyQnyssqInfo(qnyssq);
                    //查询该年度预算是否已经存在
                    List<Monthlybudgetadjustrecord> monthlybudgetadjustrecords=monthlybudgetadjustrecordMapper.selectBudgetInfoByParam(monthlybudgetadjustrecord);
                    if(!Collections.isEmpty(monthlybudgetadjustrecords)){
                        log.info("预算额度中间表已存在该年度该总账户和该分帐户和该成本中心的数据，数据为:"+JSON.toJSONString(qnyssq));
                        continue;
                    }
                    int num=0;
                    for (int i = 1; i <=12 ; i++) {
                        //转化对象数据
                        monthlybudgetadjustrecord=this.setBudgetDeatail(monthlybudgetadjustrecord,i,qnyssq);
                        //新增预算中间表数据
                        num+=monthlybudgetadjustrecordMapper.insertMonthlybudgetadjustrecord(monthlybudgetadjustrecord);
                    }
                    if(num>0){
                        ids.add(qnyssq.getId());
                    }
                }
            }
            if(!Collections.isEmpty(ids)){
                //将全年预算的状态修改为已同步
                qnyssqMapper.updateQnyssqById(ids.toArray(new String[ids.size()]));
            }


        }
    }

    @Override
    public void syncMdmCostCenter(Map<String, String> params) {

        String url0 = hxConfig.getQadurl();
        String xdomain = hxConfig.getXdomain();
        String xtoken = hxConfig.getToken();
        Integer syncResultNum0 = 0;
        Map<String, String> params0 = new HashMap<>();
        if (!CollectionUtil.isEmpty(params0)) {
            //设置请求参数
            StringBuilder arg = null ;
            arg = new StringBuilder() ;
            for(Map.Entry<String,String> entry : params0.entrySet()){
                arg.append(entry.getKey()).append("=").append(entry.getValue()).append("&") ;
            }
            url0 = url0 + "?" + arg.substring(0,arg.length()-1) ;
        }

        String result0 = HttpRestUtil.httpGetUrlWithoutEncrypt(url0, "", xdomain, "qad_ac_mstr", xtoken);
        log.info("------------------------" + JSON.toJSONString(result0));
        JSONObject jsonObject0 = JSONObject.parseObject(result0);
        if (!org.apache.commons.lang.StringUtils.isEmpty(result0)) {

            // 删除表中所有数据---start
            List<String> ids = ie6s6KmjcxxMapper.getIds();
            int count = ids.size() / 500;
            int remainder = ids.size() % 500;
            List<String> oneSubmit = null;
            for (int i = 0; i <= count; i++) {
                if (i == count) {
                    if (remainder > 0) {
                        oneSubmit = ids.subList(500 * i, 500 * i + remainder);
                        ie6s6KmjcxxMapper.deleteOldData(oneSubmit);
                    }
                } else {
                    oneSubmit = ids.subList(500 * i, 500 * (i + 1));
                    ie6s6KmjcxxMapper.deleteOldData(oneSubmit);
                }
            }
            // 删除表中所有数据---end

            JSONArray data0 = jsonObject0.getJSONArray("data");
            log.info("**列表接口返回:{}", data0);
            if (!CollectionUtils.isEmpty(data0)) {
                syncResultNum0 = data0.size();
                List<Account> accounts = new ArrayList<>();
                for (int i = 0; i < syncResultNum0; i++) {
                    JSONObject object0 = (JSONObject) data0.get(i);
                    if (object0.getBoolean("qad_ac_active")) {
                        // 账户
                        String qadAcCode = object0.getString("qad_ac_code");

                        params.put("IcAcctFrom", qadAcCode);
                        params.put("IcAcctTo", qadAcCode);
                        params.put("IcSubFrom", "");
                        params.put("IcSubTo", "");

                        // 根据一级科目code循环获取同步成本中心
                        String url = hxConfig.getQadmdmurl();
                        Integer syncResultNum = 0;
                        if (!CollectionUtil.isEmpty(params)) {
                            //设置请求参数
                            StringBuilder arg = null;
                            arg = new StringBuilder();
                            for (Map.Entry<String, String> entry : params.entrySet()) {
                                arg.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
                            }
                            url = url + "?" + arg.substring(0, arg.length() - 1);
                        }
                        // 获取QAD成本中心数据
                        String result = HttpRestUtil.httpGetUrlWithoutEncrypt(url, "", xdomain, "MdmCostCenterGet", xtoken);
                        log.info("------------------------" + JSON.toJSONString(result));
                        JSONObject jsonObject = JSONObject.parseObject(result);
                        List<Ie6s6Kmjcxx> ie6s6Kmjcxxs = new ArrayList<>();
                        if (!org.apache.commons.lang.StringUtils.isEmpty(result)) {

                            // 获取本地数据库中成本中心数据
                            JSONArray data = jsonObject.getJSONArray("data");
                            log.info("**列表接口返回:{}", data);
                            if (!CollectionUtils.isEmpty(data)) {
                                syncResultNum = data.size();
                                for (int j = 0; j < syncResultNum; j++) {
                                    boolean isNew = true;
                                    JSONObject object = (JSONObject) data.get(j);
                                    // 是否激活
                                    if (object.getBoolean("MdmCostCenterIsactive")) {
                                        Ie6s6Kmjcxx ie6s6Kmjcxx = new Ie6s6Kmjcxx();
                                        String oneCode = object.getString("MdmCostCenterGLCode");
                                        String twoCode = object.getString("MdmCostCenterDivisionCode");
                                        String oneName = object.getString("MdmCostCenterGLDescription");
                                        String twoName = object.getString("MdmCostCenterDivisionDescription");
                                        String cbzx = object.getString("MdmCostCenterCode");
                                        String yscbzxms = object.getString("MdmCostCenterDescription");
                                        if (isNew) {
                                            ie6s6Kmjcxx = this.convertKmjcxxInfo(oneCode, twoCode, oneName, twoName, cbzx, yscbzxms);
                                            ie6s6Kmjcxxs.add(ie6s6Kmjcxx);
                                        }
                                    }
                                }
                                // 插入新数据
                                if (!CollectionUtils.isEmpty(ie6s6Kmjcxxs)) {

                                    int count2 = ie6s6Kmjcxxs.size() / 500; // 自定义一次批量处理条数（不要太高，如果太大的话，可能超过mysql默认的最大长度1M的限制）
                                    int remainder2 = ie6s6Kmjcxxs.size() % 500;
                                    List<Ie6s6Kmjcxx> oneSubmit2 = null;
                                    int insertNum = 0;
                                    for (int j = 0; j <= count2; j++) {
                                        if (j == count2) {
                                            if (remainder2 > 0) {
                                                oneSubmit2 = ie6s6Kmjcxxs.subList(500 * j, 500 * j + remainder2);
                                                insertNum += ie6s6KmjcxxMapper.insertKmjcxxMultiple(oneSubmit2);
                                            }
                                        } else {
                                            oneSubmit2 = ie6s6Kmjcxxs.subList(500 * j, 500 * (j + 1));
                                            insertNum += ie6s6KmjcxxMapper.insertKmjcxxMultiple(oneSubmit2);
                                        }
                                    }

                                    int size = ie6s6Kmjcxxs.size();
                                    log.info("**成本中心数据同步插入新数据条数:{}", insertNum);
                                    log.info("**成本中心数据同步插入新数据条数:{}", size);
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    @Override
    public void syncCurrency(Map<String, String> params) {
        String url = hxConfig.getQadurl();
        String xdomain = hxConfig.getXdomain();
        String xtoken = hxConfig.getToken();
        Integer syncResultNum = 0;
        if (!CollectionUtil.isEmpty(params)) {
            //设置请求参数
            StringBuilder arg = null ;
            arg = new StringBuilder() ;
            for(Map.Entry<String,String> entry : params.entrySet()){
                arg.append(entry.getKey()).append("=").append(entry.getValue()).append("&") ;
            }
            url = url + "?" + arg.substring(0,arg.length()-1) ;
        }
        String result = HttpRestUtil.httpGetUrlWithoutEncrypt(url, "", xdomain, "qad_cu_mstr", xtoken);
        log.info("------------------------"+ JSON.toJSONString(result));
        JSONObject jsonObject = JSONObject.parseObject(result);
        if (!org.apache.commons.lang.StringUtils.isEmpty(result)) {
            List<Ie6s6CurrencyMaintain> ie6s6CurrencyMaintains = ie6s6CurrencyMaintainMapper.selectCurrency();
            List<Ie6s6CurrencyMaintain> removeCurrencys = new ArrayList<>();
            List<Ie6s6CurrencyMaintain> insertCurrencys = new ArrayList<>();
            removeCurrencys.addAll(ie6s6CurrencyMaintains);
            JSONArray data = jsonObject.getJSONArray("data");
            log.info("**列表接口返回:{}", data);
            if (!CollectionUtils.isEmpty(data)) {
                syncResultNum = data.size();
                for (int j = 0; j < syncResultNum; j++) {
                    boolean isNew = true;
                    JSONObject object = (JSONObject) data.get(j);
                    String syncHbCode = object.getString("qad_cu_curr");
                    for (Ie6s6CurrencyMaintain ie6s6CurrencyMaintain : ie6s6CurrencyMaintains) {
                        String hbCode = ie6s6CurrencyMaintain.getHbCode();
                        if (!StringUtils.isEmpty(syncHbCode) && syncHbCode.equals(hbCode)) {
                            IntStream.range(0, removeCurrencys.size()).filter(i->removeCurrencys.get(i).getHbCode().equals(hbCode)).boxed().findFirst().map(i->removeCurrencys.remove((int)i));
                            isNew = false;
                            break;
                        }
                    }
                    if (isNew) {
                        Ie6s6CurrencyMaintain ie6s6CurrencyMaintain = this.convertCurrencyInfo(syncHbCode, object.getString("qad_cu_desc"));
                        insertCurrencys.add(ie6s6CurrencyMaintain);
                    }
                }
                if (!CollectionUtils.isEmpty(removeCurrencys)) {
                    int size = removeCurrencys.size();
                    String[] ids = new String[size];
                    for (int i = 0; i < size; i++) {
                        ids[i] = removeCurrencys.get(i).getId();
                    }
                    ie6s6CurrencyMaintainMapper.deleteCurrencyMaintain(ids);
                }
                if (!CollectionUtils.isEmpty(insertCurrencys)) {
                    ie6s6CurrencyMaintainMapper.insertCurrencyMaintain(insertCurrencys);
                }
            }
        }
    }

    @Override
    public int syncAccount(Map<String, String> params) {
        String url = hxConfig.getQadurl();
        String xdomain = hxConfig.getXdomain();
        String xtoken = hxConfig.getToken();
        Integer syncResultNum = 0;
        if (!CollectionUtil.isEmpty(params)) {
            //设置请求参数
            StringBuilder arg = null ;
            arg = new StringBuilder() ;
            for(Map.Entry<String,String> entry : params.entrySet()){
                arg.append(entry.getKey()).append("=").append(entry.getValue()).append("&") ;
            }
            url = url + "?" + arg.substring(0,arg.length()-1) ;
        }
        String result = HttpRestUtil.httpGetUrlWithoutEncrypt(url, "", xdomain, "qad_ac_mstr", xtoken);
        log.info("------------------------"+ JSON.toJSONString(result));
        JSONObject jsonObject = JSONObject.parseObject(result);
        if (!org.apache.commons.lang.StringUtils.isEmpty(result)) {
            JSONArray data = jsonObject.getJSONArray("data");
            log.info("**列表接口返回:{}", data);
            if (!CollectionUtils.isEmpty(data)) {
                syncResultNum = data.size();
                List<Account> accounts = new ArrayList<>();
                for (int i = 0; i < syncResultNum; i++) {
                    JSONObject object = (JSONObject) data.get(i);
                    if (object.getBoolean("qad_ac_active")) {
                        // 账户
                        String qadAcCode = object.getString("qad_ac_code");
                        // 描述
                        String qadAcDesc = object.getString("qad_ac_desc");
                        Account account = this.accountInfo(qadAcCode, qadAcDesc);
                        accounts.add(account);
                    }
                }
                if (CollectionUtils.isNotEmpty(accounts)) {
                    syncResultNum = yjkmjcxxwhMapper.insertAccounts(accounts);
                } else {
                    return 0;
                }
            }
        }
        return syncResultNum;
    }

    @Override
    public int syncSubAccount(Map<String, String> params) {
        String url = hxConfig.getQadurl();
        String xdomain = hxConfig.getXdomain();
        String xtoken = hxConfig.getToken();
        Integer syncResultNum = 0;
        if (!CollectionUtil.isEmpty(params)) {
            //设置请求参数
            StringBuilder arg = null ;
            arg = new StringBuilder() ;
            for(Map.Entry<String,String> entry : params.entrySet()){
                arg.append(entry.getKey()).append("=").append(entry.getValue()).append("&") ;
            }
            url = url + "?" + arg.substring(0,arg.length()-1) ;
        }
        String result = HttpRestUtil.httpGetUrlWithoutEncrypt(url, "", xdomain, "qad_sb_mstr", xtoken);
        log.info("------------------------"+ JSON.toJSONString(result));
        JSONObject jsonObject = JSONObject.parseObject(result);
        if (!org.apache.commons.lang.StringUtils.isEmpty(result)) {
            JSONArray data = jsonObject.getJSONArray("data");
            log.info("**列表接口返回:{}", data);
            if (!CollectionUtils.isEmpty(data)) {
                syncResultNum = data.size();
                List<SubAccount> accounts = new ArrayList<>();
                for (int i = 0; i < syncResultNum; i++) {
                    JSONObject object = (JSONObject) data.get(i);
                    if (object.getBoolean("qad_sb_active")) {
                        // 账户
                        String qadAcCode = object.getString("qad_sb_sub");
                        // 描述
                        String qadAcDesc = object.getString("qad_sb_desc");
                        SubAccount account = this.subAccountInfo(qadAcCode, qadAcDesc);
                        accounts.add(account);
                    }
                }
                if (CollectionUtils.isNotEmpty(accounts)) {
                    syncResultNum = ejkmjcxxwhMapper.insertAccounts(accounts);
                } else {
                    return 0;
                }
            }
        }
        return syncResultNum;
    }

    private Monthlybudgetadjustrecord setBudgetDeatail(Monthlybudgetadjustrecord monthlybudgetadjustrecord,int i,Qnyssq qnyssq) {
        monthlybudgetadjustrecord.setMonth(String.valueOf(i));
        if(i==1){
            if(qnyssq.getOneed()==null){
                monthlybudgetadjustrecord.setAvailableQuota(new BigDecimal(0));
                monthlybudgetadjustrecord.setStartLimit(new BigDecimal(0));
            }else{
                monthlybudgetadjustrecord.setAvailableQuota(qnyssq.getOneed());
                monthlybudgetadjustrecord.setStartLimit(qnyssq.getOneed());
            }
        }else if(i==2){
            if(qnyssq.getTwoed()==null){
                monthlybudgetadjustrecord.setAvailableQuota(new BigDecimal(0));
                monthlybudgetadjustrecord.setStartLimit(new BigDecimal(0));
            }else{
                monthlybudgetadjustrecord.setAvailableQuota(qnyssq.getTwoed());
                monthlybudgetadjustrecord.setStartLimit(qnyssq.getTwoed());
            }
        }else if(i==3){
            if(qnyssq.getThreeed()==null){
                monthlybudgetadjustrecord.setAvailableQuota(new BigDecimal(0));
                monthlybudgetadjustrecord.setStartLimit(new BigDecimal(0));
            }else{
                monthlybudgetadjustrecord.setAvailableQuota(qnyssq.getThreeed());
                monthlybudgetadjustrecord.setStartLimit(qnyssq.getThreeed());
            }
        }else if(i==4){
            if(qnyssq.getFoured()==null){
                monthlybudgetadjustrecord.setAvailableQuota(new BigDecimal(0));
                monthlybudgetadjustrecord.setStartLimit(new BigDecimal(0));
            }else{
                monthlybudgetadjustrecord.setAvailableQuota(qnyssq.getFoured());
                monthlybudgetadjustrecord.setStartLimit(qnyssq.getFoured());
            }
        }else if(i==5){
            if(qnyssq.getFiveed()==null){
                monthlybudgetadjustrecord.setAvailableQuota(new BigDecimal(0));
                monthlybudgetadjustrecord.setStartLimit(new BigDecimal(0));
            }else{
                monthlybudgetadjustrecord.setAvailableQuota(qnyssq.getFiveed());
                monthlybudgetadjustrecord.setStartLimit(qnyssq.getFiveed());
            }
        }else if(i==6){
            if(qnyssq.getSixed()==null){
                monthlybudgetadjustrecord.setAvailableQuota(new BigDecimal(0));
                monthlybudgetadjustrecord.setStartLimit(new BigDecimal(0));
            }else{
                monthlybudgetadjustrecord.setAvailableQuota(qnyssq.getSixed());
                monthlybudgetadjustrecord.setStartLimit(qnyssq.getSixed());
            }
        }else if(i==7){
            if(qnyssq.getSevened()==null){
                monthlybudgetadjustrecord.setAvailableQuota(new BigDecimal(0));
                monthlybudgetadjustrecord.setStartLimit(new BigDecimal(0));
            }else{
                monthlybudgetadjustrecord.setAvailableQuota(qnyssq.getSevened());
                monthlybudgetadjustrecord.setStartLimit(qnyssq.getSevened());
            }
        }else if(i==8){
            if(qnyssq.getEighted()==null){
                monthlybudgetadjustrecord.setAvailableQuota(new BigDecimal(0));
                monthlybudgetadjustrecord.setStartLimit(new BigDecimal(0));
            }else{
                monthlybudgetadjustrecord.setAvailableQuota(qnyssq.getEighted());
                monthlybudgetadjustrecord.setStartLimit(qnyssq.getEighted());
            }
        }else if(i==9){
            if(qnyssq.getNineed()==null){
                monthlybudgetadjustrecord.setAvailableQuota(new BigDecimal(0));
                monthlybudgetadjustrecord.setStartLimit(new BigDecimal(0));
            }else{
                monthlybudgetadjustrecord.setAvailableQuota(qnyssq.getNineed());
                monthlybudgetadjustrecord.setStartLimit(qnyssq.getNineed());
            }
        }else if(i==10){
            if(qnyssq.getTened()==null){
                monthlybudgetadjustrecord.setAvailableQuota(new BigDecimal(0));
                monthlybudgetadjustrecord.setStartLimit(new BigDecimal(0));
            }else{
                monthlybudgetadjustrecord.setAvailableQuota(qnyssq.getTened());
                monthlybudgetadjustrecord.setStartLimit(qnyssq.getTened());
            }
        }else if(i==11){
            if(qnyssq.getElevened()==null){
                monthlybudgetadjustrecord.setAvailableQuota(new BigDecimal(0));
                monthlybudgetadjustrecord.setStartLimit(new BigDecimal(0));
            }else{
                monthlybudgetadjustrecord.setAvailableQuota(qnyssq.getElevened());
                monthlybudgetadjustrecord.setStartLimit(qnyssq.getElevened());
            }
        }else if(i==12){
            if(qnyssq.getTwelveed()==null){
                monthlybudgetadjustrecord.setAvailableQuota(new BigDecimal(0));
                monthlybudgetadjustrecord.setStartLimit(new BigDecimal(0));
            }else{
                monthlybudgetadjustrecord.setAvailableQuota(qnyssq.getTwelveed());
                monthlybudgetadjustrecord.setStartLimit(qnyssq.getTwelveed());
            }
        }
        return monthlybudgetadjustrecord;
    }

    //将年度预算信息转化为预算中间表信息
    private Monthlybudgetadjustrecord copyQnyssqInfo(Qnyssq qnyssq) {
        Monthlybudgetadjustrecord monthlybudgetadjustrecord=new Monthlybudgetadjustrecord();
        monthlybudgetadjustrecord.setYear(qnyssq.getNf());
//        monthlybudgetadjustrecord.setOnesubject(qnyssq.getOneaccountcode());
        monthlybudgetadjustrecord.setOneSubject(qnyssq.getOneaccountcode());
        monthlybudgetadjustrecord.setTwoSubject(qnyssq.getTwoaccountcode());
        List<Map<String,String>> listFygsbm= (List<Map<String,String>>) JSONArray.parse(qnyssq.getFygsbm());
        if(!Collections.isEmpty(listFygsbm)){
            //费用归属部门
            String fygsbm=listFygsbm.get(0).get("id");
            monthlybudgetadjustrecord.setBelongDepart(fygsbm);
        }

        List<Map<String,String>> listFytbbm= (List<Map<String,String>>) JSONArray.parse(qnyssq.getFytbbm());
        if(!Collections.isEmpty(listFytbbm)){
            //费用填报部门
            String fytbbm=listFytbbm.get(0).get("id");
            monthlybudgetadjustrecord.setFillInDepart(fytbbm);
        }

        monthlybudgetadjustrecord.setCostCenter(qnyssq.getYscbzx());
        monthlybudgetadjustrecord.setCreatedTime(new Date());
        monthlybudgetadjustrecord.setCreatedBy(qnyssq.getCreater());
        return monthlybudgetadjustrecord;
    }

    public Ie6s6Kmjcxx convertKmjcxxInfo(String oneCode, String twoCode, String oneName, String twoName, String cbzx, String yscbzxms) {
        Ie6s6Kmjcxx ie6s6Kmjcxx=new Ie6s6Kmjcxx();
//        String uuid= UUID.randomUUID().toString().replaceAll("-","");
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(oneCode);
        stringBuilder.append(twoCode);
        stringBuilder.append(cbzx);
        String id = stringBuilder.toString();
        ie6s6Kmjcxx.setId(id);
        ie6s6Kmjcxx.setOneaccountcode(oneCode);
        ie6s6Kmjcxx.setTwoaccountcode(twoCode);
        ie6s6Kmjcxx.setOneaccountname(oneName);
        ie6s6Kmjcxx.setTwoaccountname(twoName);
//        ie6s6Kmjcxx.setName(oneName+"-"+twoName);
        ie6s6Kmjcxx.setName(oneCode + "-" + twoCode + "-" + cbzx);
        ie6s6Kmjcxx.setCreater("");
        ie6s6Kmjcxx.setCreateddeptid("");
        ie6s6Kmjcxx.setOwner("");
        ie6s6Kmjcxx.setOwnerdeptid("");
        ie6s6Kmjcxx.setCreatedtime(new Date());
        ie6s6Kmjcxx.setModifier("");
        ie6s6Kmjcxx.setModifiedtime(new Date());
//        ie6s6QadgysMaintain.setSequenceno();
        ie6s6Kmjcxx.setSequencestatus("COMPLETED");
        ie6s6Kmjcxx.setOwnerdeptquerycode("1");
        ie6s6Kmjcxx.setYyxt("QAD");
        ie6s6Kmjcxx.setYscbzx(cbzx);
        ie6s6Kmjcxx.setYscbzxms(yscbzxms);
        ie6s6Kmjcxx.setIsfk("否");
        return ie6s6Kmjcxx;
    }

    public Ie6s6CurrencyMaintain convertCurrencyInfo(String qadCuCurr, String qadCuDesc){
        Ie6s6CurrencyMaintain ie6s6CurrencyMaintain = new Ie6s6CurrencyMaintain();
        String uuid= UUID.randomUUID().toString().replaceAll("-","");
        ie6s6CurrencyMaintain.setId(uuid);
        ie6s6CurrencyMaintain.setName(qadCuCurr + "," + qadCuDesc);
        ie6s6CurrencyMaintain.setCreater("");
        ie6s6CurrencyMaintain.setCreatedDeptId("");
        ie6s6CurrencyMaintain.setOwner("");
        ie6s6CurrencyMaintain.setOwnerDeptId("");
        ie6s6CurrencyMaintain.setCreatedTime(new Date());
        ie6s6CurrencyMaintain.setModifier("");
        ie6s6CurrencyMaintain.setModifiedTime(new Date());
        ie6s6CurrencyMaintain.setSequenceStatus("COMPLETED");
        ie6s6CurrencyMaintain.setOwnerDeptQueryCode("1");
        ie6s6CurrencyMaintain.setHbCode(qadCuCurr);
        ie6s6CurrencyMaintain.setHbName(qadCuDesc);
        return ie6s6CurrencyMaintain;
    }

    public Account accountInfo(String qadAcCode, String qadAcDesc){
        Account account = new Account();
        String uuid= UUID.randomUUID().toString().replaceAll("-","");
        account.setId(uuid);
        account.setName(qadAcCode + "," + qadAcDesc);
        account.setCreater("");
        account.setCreatedDeptId("");
        account.setOwner("");
        account.setOwnerDeptId("");
        account.setCreatedTime(new Date());
        account.setModifier("");
        account.setModifiedTime(new Date());
        account.setSequenceStatus("COMPLETED");
        account.setOwnerDeptQueryCode("1");
        account.setOneSubjectCode(qadAcCode);
        account.setOneSubjectName(qadAcDesc);
        account.setYyxt("QAD");
        return account;
    }

    public SubAccount subAccountInfo(String qadAcCode, String qadAcDesc){
        SubAccount account = new SubAccount();
        String uuid= UUID.randomUUID().toString().replaceAll("-","");
        account.setId(uuid);
        account.setName(qadAcCode + "," + qadAcDesc);
        account.setCreater("");
        account.setCreatedDeptId("");
        account.setOwner("");
        account.setOwnerDeptId("");
        account.setCreatedTime(new Date());
        account.setModifier("");
        account.setModifiedTime(new Date());
        account.setSequenceStatus("COMPLETED");
        account.setOwnerDeptQueryCode("1");
        account.setTwoSubjectCode(qadAcCode);
        account.setTwoSubjectName(qadAcDesc);
        account.setYyxt("QAD");
        return account;
    }

    @Override
    public int syncCCToBPM(Map<String,String> params) {
        String url = hxConfig.getQadurl();
//        String xcorp="04693esd-1564-4635-4s4e-6db6s6a8b95d";
        String xdomain = hxConfig.getXdomain();
        String xtoken = hxConfig.getToken();
        Integer syncResultNum = 0;
        if (!CollectionUtil.isEmpty(params)) {
            //设置请求参数
            StringBuilder arg = null ;
            arg = new StringBuilder() ;
            for(Map.Entry<String,String> entry : params.entrySet()){
                arg.append(entry.getKey()).append("=").append(entry.getValue()).append("&") ;
            }
            url = url + "?" + arg.substring(0,arg.length()-1) ;
        }
        String result = HttpRestUtil.httpGetUrlWithoutEncrypt(url,"", xdomain, "qad_cc_mstr", xtoken);
        log.info("------------------------"+ JSON.toJSONString(result));
        JSONObject jsonObject = JSONObject.parseObject(result);
        List<Ie6s6cbzxwhjcxx> cbzxwhjcxxes = new ArrayList<>();
        if (!org.apache.commons.lang.StringUtils.isEmpty(result)) {
            JSONArray data = jsonObject.getJSONArray("data");
            log.info("**列表接口返回:{}", data);
            if (!CollectionUtils.isEmpty(data)) {
                syncResultNum = data.size();
                for (int i = 0; i < syncResultNum; i++) {
                    JSONObject object = (JSONObject) data.get(i);
                    // 是否激活
                    if (object.getBoolean("qad_cc_active")) {
                        Ie6s6cbzxwhjcxx ie6s6cbzxwhjcxx = new Ie6s6cbzxwhjcxx();
                        //成本中心
                        String cbzx = object.getString("qad_cc_ctr");
                        //描述
                        String ms =object.getString("qad_cc_desc");
                        ie6s6cbzxwhjcxx=this.converCCTOBPMInfo(cbzx,ms);
                        cbzxwhjcxxes.add(ie6s6cbzxwhjcxx);
                    }
                }
                if (!CollectionUtils.isEmpty(cbzxwhjcxxes)) {
                    syncResultNum= ie6s6cbzxwhjcxxMapper.insertCCtoBPM(cbzxwhjcxxes);
                }else {
                    return 0;
                }
            }
        }
                return syncResultNum;
    }

    @Override
    public void syncKjdwxx() {
        String url = hxConfig.getQadurl();
//        String xcorp="04693esd-1564-4635-4s4e-6db6s6a8b95d";
        String xdomain = hxConfig.getXdomain();
        String xtoken = hxConfig.getToken();
        String result = HttpRestUtil.httpGetUrlWithoutEncrypt(url,"", xdomain, "qad_en_mstr", xtoken);
        log.info("------------------------"+ JSON.toJSONString(result));
        JSONObject jsonObject = JSONObject.parseObject(result);
        List<Ie6s6Kjdwxx> ie6s6Kjdwxxes = new ArrayList<>();
        int num=0;
        if (!org.apache.commons.lang.StringUtils.isEmpty(result)) {
            JSONArray data = jsonObject.getJSONArray("data");
            log.info("**列表接口返回:{}", data);
            if (!CollectionUtils.isEmpty(data)) {
                for (int i = 0; i < data.size(); i++) {
                    JSONObject object = (JSONObject) data.get(i);
                    // 是否激活
                    if (object.getBoolean("qad_en_active")) {
                        //成本中心
                        String code = object.getString("qad_en_entity");
                        //描述
                        String name =object.getString("qad_en_name");
                        //所属公司
                        String ssgs =object.getString("qad_en_domain");
                        Ie6s6Kjdwxx ie6s6Kjdwxx=this.converIe6s6KjdwxxInfo(code,name,ssgs);
                        ie6s6Kjdwxxes.add(ie6s6Kjdwxx);
                    }
                }
                if (!CollectionUtils.isEmpty(ie6s6Kjdwxxes)) {
                    num= ie6s6KjdwxxMapper.insertKjdwxx(ie6s6Kjdwxxes);
                }
            }
        }
        log.info("-----------同步会计单位信息条数共{}条------------",num);
    }

    public Ie6s6Kjdwxx converIe6s6KjdwxxInfo(String code,String name,String ssgs){
        Ie6s6Kjdwxx ie6s6Kjdwxx = new Ie6s6Kjdwxx();
        String uuid= UUID.randomUUID().toString().replaceAll("-","");
        ie6s6Kjdwxx.setId(uuid);
        ie6s6Kjdwxx.setCreater("");
        ie6s6Kjdwxx.setCreatedDeptId("");
        ie6s6Kjdwxx.setOwner("");
        ie6s6Kjdwxx.setOwnerDeptId("");
        ie6s6Kjdwxx.setCreatedTime(new Date());
        ie6s6Kjdwxx.setModifier("");
        ie6s6Kjdwxx.setModifiedTime(new Date());
        ie6s6Kjdwxx.setSequenceStatus("COMPLETED");
        ie6s6Kjdwxx.setOwnerDeptQueryCode("1");
        ie6s6Kjdwxx.setKjdwCode(code);
        ie6s6Kjdwxx.setKjdwName(name);
        ie6s6Kjdwxx.setSsgs(ssgs);
        return ie6s6Kjdwxx;
    }

    public Ie6s6cbzxwhjcxx converCCTOBPMInfo(String cbzx,String ms){
        Ie6s6cbzxwhjcxx ie6s6cbzxwhjcxx = new Ie6s6cbzxwhjcxx();
        String uuid= UUID.randomUUID().toString().replaceAll("-","");
        ie6s6cbzxwhjcxx.setId(uuid);
        ie6s6cbzxwhjcxx.setCreater("");
        ie6s6cbzxwhjcxx.setCreateddeptid("");
        ie6s6cbzxwhjcxx.setOwner("");
        ie6s6cbzxwhjcxx.setOwnerdeptid("");
        ie6s6cbzxwhjcxx.setCreatedtime(new Date());
        ie6s6cbzxwhjcxx.setModifier("");
        ie6s6cbzxwhjcxx.setModifiedtime(new Date());
        ie6s6cbzxwhjcxx.setSequencestatus("COMPLETED");
        ie6s6cbzxwhjcxx.setOwnerdeptquerycode("1");
        ie6s6cbzxwhjcxx.setCbzxname(ms);
        ie6s6cbzxwhjcxx.setCbzxcode(cbzx);
        ie6s6cbzxwhjcxx.setYyxt("QAD");
        return ie6s6cbzxwhjcxx;
    }

    @Override
    public int syncDep() {
        String accessToken = DingDingUtil.getAccessToken();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar calendar = new GregorianCalendar();
        calendar.setTime(new Date());
        calendar.add(Calendar.DATE,-1);
        //获取昨天的时间
        String yesday = sdf.format(calendar.getTime());
        List<Dept> deps = syncddmapper.getdepinfo();
        for (int i = 0; i <deps.size() ; i++) {
            Dept dept = deps.get(i);
            //部门id
            String bmbm = dept.getBmbm();
            String bmmc = dept.getBmmc().replaceAll("-","");
            //公司id
            String gsid = dept.getZzbm();
            //中间表中hrid对应的钉钉id
            String selecedep=null;
            //通过部门id和公司id对应关系查询
            selecedep = syncddmapper.selecedepByBmId(bmbm,gsid);

            //存在则判断是否修改
            if (!StringUtils.isEmpty(selecedep)) {
                //通过是修改时间判断是否修改
                //修改时间
                String modifitime = dept.getModifitime().substring(0,10);

                //时间相同为修改过
               if (modifitime.equals(yesday)){
                    Long depid=Long.parseLong(selecedep);
                    //获取父部门id
                    String fjbm = dept.getFjbm();
                    if (StringUtils.isNotEmpty(fjbm)){
                        //父部门的钉钉id
                        String fjdddepid = syncddmapper.selecedepByBmId(fjbm, gsid);
                        Long parentId=Long.parseLong(fjdddepid);
                        DingDingUtil.updateDep(accessToken,depid,bmmc,parentId);
                    }else {
                        //父级部门为空则使用组织编码
                        String zzbm = dept.getZzbm();
                        String ddid= syncddmapper.selecedepByBmId(zzbm, zzbm);
                        Long parentId = Long.parseLong(ddid);
                        DingDingUtil.updateDep(accessToken,depid,bmmc,parentId);
                    }
                    //判断删除标志
                    if ("1".equals(dept.getIsdel())){
                        System.out.println("删除部门");
                        Long aLong =DingDingUtil.deleteDep(accessToken,depid);
                        if (aLong.equals("60005")){
                            log.info("不允许删除有成员的部门");
                        }else{
                            syncddmapper.deleteDepidFromTable(selecedep);
                        }
                    }
               }
            }
            //不存在则开始创建
            if (StringUtils.isEmpty(selecedep)){
                Boolean flag=false;
                while (!flag){
                    flag= loopParentDep(accessToken, dept);
                }
            }
        }
        return 0;
    }

    @Override
    public void incrementdep(){
        String accessToken =DingDingUtil.getAccessToken();
        List<Dept> depts = syncddmapper.incrementdep();
        if (CollectionUtils.isEmpty(depts)){
            log.info("部门增量表为空，同步结束");
            return;
        }else {
            for (int i = 0; i < depts.size(); i++) {
                Dept dept = depts.get(i);
                //部门id
                String bmbm = dept.getBmbm();
                //公司id
                String gsid = dept.getZzbm();
                //中间表中hrid对应的钉钉id
                String selecedep=null;
                //通过部门id和公司id对应关系查询
                selecedep = syncddmapper.selecedepByBmId(bmbm,gsid);
                //不存在则开始创建
                if (StringUtils.isEmpty(selecedep)){
                    Boolean flag=false;
                    while (!flag){
                        flag= loopParentDep(accessToken, dept);
                    }
                }
            }
        }
    }

    @Override
    public int syncDD(){
        String accessToken =DingDingUtil.getAccessToken();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar calendar = new GregorianCalendar();
        //级别编码
        String jbcode=null;
        //转义符，用于设置钉钉拓展字段
//        String zy="\"";
        List<DingDingUser> users = syncddmapper.getuserinfo();
        int size = users.size();
        for (int i = 0; i < size; i++) {
            DingDingUser ncuser = users.get(i);
            //工号
            String jobnumber = ncuser.getJobnumber();
            //员工姓名
            String name = ncuser.getName();
            //公司编码
            String companyid = ncuser.getCompanyid();
            //公司名称
            String companyname = ncuser.getCompanyname();
            //部门编码
            String deptid = ncuser.getDeptid();
            //邮箱
            String email = ncuser.getEmail();
            //岗位
            String title = ncuser.getTitle();
            //入职时间
            String createdate = ncuser.getCreatedate();
            long rzsj = 0;
            try {
                rzsj = sdf.parse(createdate).getTime();
            } catch (ParseException e) {
                e.printStackTrace();
            }
            //用hr级别编码查询对应的级别编码
            String jbbm = ncuser.getJbbm();
            jbcode = syncddmapper.selectLevelCode(jbbm);
            if ("021".equals(jbbm)){
                String xzwcode = ncuser.getXzwcode();
                if ("01501".equals(xzwcode)){
                    jbcode="J0";
                }else if("01502".equals(xzwcode)){
                    jbcode="P0";
                }else if("01503".equals(xzwcode)){
                    jbcode="G0";
                }else {
                    jbcode="J0";
                }
            }
            //级别名称
            String jbmc = ncuser.getXzwname();
            //获取所在部门钉钉id
            String dddepid = syncddmapper.selecedepByBmId(deptid, companyid);
            //获取公司缩写
            Dept org = syncddmapper.selectOrg(companyid);
            String compabb = org.getCompabb();
//            //设置拓展字段内容
//            String excetion="{"+zy+"公司代码"+zy+":"+zy+companyid+zy+","+
//                    zy+"公司缩写"+zy+":"+zy+compabb+zy+","+
//                    zy+"级别代码"+zy+":"+zy+jbcode+zy+","+
//                    zy+"所属公司"+zy+":"+zy+companyname+zy+","+
//                    zy+"员工级别"+zy+":"+zy+jbmc+zy+"}";
            Map map = new HashMap<>();
            map.put("公司代码",companyid);
            map.put("公司缩写",compabb);
            map.put("级别代码",jbcode);
            map.put("所属公司",companyname);
            map.put("员工级别",jbmc);
            String excetion = JSON.toJSONString(map);

            //电话号码
            String mobile =ncuser.getMobile();
            String ddid=null;
            //通过电话号码判断是否存在钉钉里
            OapiV2UserGetbymobileResponse rsp =DingDingUtil.getUseridByMobile(accessToken, mobile);
            if ("ok".equals(rsp.getErrmsg())){
                ddid=rsp.getResult().getUserid();
            }
            //为空则表示不存在钉钉，并创建用户
            if (StringUtils.isEmpty(ddid)){
                DingDingUtil.createUser(accessToken,jobnumber,name,mobile,title,email,dddepid,excetion,rzsj);
            }else {
                //先判断是否删除
                if ("1".equals(ncuser.getIsdel())){
                    DingDingUtil.deleteUser(accessToken,ddid);
                    log.info("删除了用户:{}",name);
                }else {
                    //通过钉钉id获取用户信息
                    OapiV2UserGetResponse response =DingDingUtil.getUserInfoById(accessToken,ddid);
                    String djobnumber = response.getResult().getJobNumber();
                    String dexcetion = response.getResult().getExtension();
                    String dtitle = response.getResult().getTitle();
                    Long hiredDate = response.getResult().getHiredDate();
                    //补全工号、拓展字段、职位、入职时间
                    if (StringUtils.isEmpty(djobnumber)
                            ||!excetion.equals(dexcetion)
                            ||(StringUtils.isEmpty(dtitle)&&title!=null)
                            ||hiredDate==null){
                        log.info("{}进行信息补全",name);
                        DingDingUtil.updateUser(accessToken,ddid,null,title,null,jobnumber,null,excetion,rzsj);
                    }
                    //获取昨天的时间
                    calendar.setTime(new Date());
                    calendar.add(Calendar.DATE,-1);
                    String yesday = sdf.format(calendar.getTime());

                    //判断岗位信息是否修改
                    //修改人员岗位信息
                    //任职时间，判断是否修改部门
                    String indutydate = ncuser.getIndutydate();
                    if(!StringUtils.isEmpty(indutydate)){
                        indutydate=indutydate.substring(0,10);
                        if (indutydate.equals(yesday)){
                            log.info("{}岗位变更",name);
                            DingDingUtil.updateUser(accessToken,ddid,dddepid);
                            log.info("{}的岗位为:{}",name,dddepid);
                        }
                    }

                    //修改时间,判断人员基本信息是否修改
                    String modifitime = ncuser.getModifytime();
                    if (!StringUtils.isEmpty(modifitime)){
                        modifitime=modifitime.substring(0,10);
                        //修改人员基本信息
                        if (modifitime.equals(yesday)){
                            log.info("{}基础信息变更",name);
                            DingDingUtil.updateUser(accessToken,ddid,name,title,jobnumber,email,dddepid,excetion,rzsj);
                        }
                    }else {
                        DingDingUtil.updateUser(accessToken,ddid,name,title,jobnumber,email,dddepid,excetion,rzsj);
                    }
                }
            }
            log.info("当前工号：{},序号：{}",jobnumber,i+1);
        }
        return 0;
    }

    @Override
    public void incrementuser(){
        String accessToken =DingDingUtil.getAccessToken();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        //级别编码
        String jbcode=null;
        List<DingDingUser> users = syncddmapper.incrementuser();
        if (CollectionUtils.isEmpty(users)){
            log.info("用户增量表为空，同步结束");
            return;
        }
        int size = users.size();
        for (int i = 0; i < size; i++) {
            DingDingUser ncuser = users.get(i);
            //工号
            String jobnumber = ncuser.getJobnumber();
            //员工姓名
            String name = ncuser.getName();
            //公司编码
            String companyid = ncuser.getCompanyid();
            //公司名称
            String companyname = ncuser.getCompanyname();
            //部门编码
            String deptid = ncuser.getDeptid();
            //邮箱
            String email = ncuser.getEmail();
            //岗位
            String title = ncuser.getTitle();
            //入职时间
            String createdate = ncuser.getCreatedate();
            long rzsj = 0;
            try {
                rzsj = sdf.parse(createdate).getTime();
            } catch (ParseException e) {
                e.printStackTrace();
            }
            //用hr级别编码查询对应的级别编码
            String jbbm = ncuser.getJbbm();
            jbcode = syncddmapper.selectLevelCode(jbbm);
            //当级别为员工时，进行判断
            if ("021".equals(jbbm)){
                String xzwcode = ncuser.getXzwcode();
                if ("01501".equals(xzwcode)){
                    jbcode="J0";
                }else if("01502".equals(xzwcode)){
                    jbcode="P0";
                }else if("01503".equals(xzwcode)){
                    jbcode="G0";
                }else {
                    jbcode="J0";
                }
            }
            //级别名称
            String jbmc = ncuser.getXzwname();
            //获取所在部门钉钉id
            String dddepid = syncddmapper.selecedepByBmId(deptid, companyid);
            //获取公司缩写
            Dept org = syncddmapper.selectOrg(companyid);
            String compabb = org.getCompabb();
            //设置拓展字段内容
            Map map = new HashMap<>();
            map.put("公司代码",companyid);
            map.put("公司缩写",compabb);
            map.put("级别代码",jbcode);
            map.put("所属公司",companyname);
            map.put("员工级别",jbmc);
            String excetion = JSON.toJSONString(map);

            //电话号码
            String mobile =ncuser.getMobile();
            //通过电话号码判断是否存在钉钉里
            OapiV2UserGetbymobileResponse rsp =DingDingUtil.getUseridByMobile(accessToken, mobile);
            if ("ok".equals(rsp.getErrmsg())){
                log.info("用户："+name+"已加入钉钉");
            }else {
                DingDingUtil.createUser(accessToken,jobnumber,name,mobile,title,email,dddepid,excetion,rzsj);
            }
        }
    }



    /**
     * 遍历部门id，拿到所有部门id
     */
    public  List<Long>  bl(String access_token,List<Long> bmid) throws ApiException {
        List<Long> child=new ArrayList<>();
        List<Long> result=new ArrayList<>();
        for (Long depid:bmid) {
            child.add(depid);
        }
        result.addAll(child);
        for (Long depid: child){
            List<Long> allDepId2 =DingDingUtil.getAllDepId(access_token, depid);
            if (!CollectionUtils.isEmpty(allDepId2)){
                result.addAll(bl(access_token,allDepId2));
            }
        }
        return result;
    }



    /**
     * 创建部门
     */
    public Boolean  loopParentDep(String access_token,Dept dept){
        String bmbm = dept.getBmbm();
        String gsid= dept.getZzbm();
        String s1 = syncddmapper.selecedepByBmId(bmbm, gsid);
        if (!StringUtils.isEmpty(s1)){
            return true;
        }
        String fjbm = dept.getFjbm();
        //如果父级编码为空则公司下部门
        if (StringUtils.isEmpty(fjbm)){
            Dept org = syncddmapper.selectOrg(gsid);
            String orgbmbm = org.getBmbm();
            String orgbmmc = org.getBmmc().replaceAll("-","");
            String orgdid = syncddmapper.selecedepByBmId(orgbmbm, null);
            if (StringUtils.isEmpty(orgdid)){
                //公司不存在，在集团下创建公司
                String uuid=UUID.randomUUID().toString().replaceAll("-","");
                Long ddid = DingDingUtil.createDep(access_token, 1L, orgbmmc);
                syncddmapper.insertintoDeptable(uuid,ddid,orgbmmc,orgbmbm,orgbmbm);
                return  false;
            }else{
                //在该公司下创建部门
                String bmmc = dept.getBmmc().replaceAll("-","");
                Long parentid=Long.parseLong(orgdid);
                Long ddid = DingDingUtil.createDep(access_token,parentid, bmmc);
                String uuid=UUID.randomUUID().toString().replaceAll("-","");
                syncddmapper.insertintoDeptable(uuid,ddid,bmmc,bmbm,orgbmbm);
                return true;
                }
        }else{
            //父级编码不为空，则查询父部门是否存在
            String s = syncddmapper.selecedepByBmId(fjbm, gsid);
            if (StringUtils.isEmpty(s)){
                Dept dep = syncddmapper.getDepById(fjbm, gsid);
                loopParentDep(access_token,dep);
            }else {
                //父部门存在则在父部门下创建
                String uuid=UUID.randomUUID().toString().replaceAll("-","");
                String bmmc = dept.getBmmc().replaceAll("-","");
                Long parentid=Long.parseLong(s);
                Long ddid=DingDingUtil.createDep(access_token,parentid,bmmc);
                syncddmapper.insertintoDeptable(uuid,ddid,bmmc,bmbm,gsid);
                return  false;
            }
        }
        return false;
        }

    @Override
    public List<DingDingUser> getUserInfo() {
        List<DingDingUser> users = syncddmapper.getuserinfo();
        String jbcode=null;
        int size = users.size();
        for (int i = 0; i < size; i++) {
            DingDingUser ncuser = users.get(i);
            if ("0".equals(ncuser.getIsdel())){
                ncuser.setWorkingstate(1);
            }else {
                ncuser.setWorkingstate(0);
            }
            if ("2".equals(ncuser.getSex())){
                ncuser.setSex(0);
            }
            //用hr级别编码查询对应的级别编码
            String jbbm = ncuser.getJbbm();
            jbcode = syncddmapper.selectLevelCode(jbbm);
            if ("021".equals(jbbm)){
                String xzwcode = ncuser.getXzwcode();
                if ("01501".equals(xzwcode)){
                    jbcode="J0";
                }else if("01502".equals(xzwcode)){
                    jbcode="P0";
                }else if("01503".equals(xzwcode)){
                    jbcode="G0";
                }else {
                    jbcode="J0";
                }
            }

            ncuser.setJbbm(jbcode);
        }
        return users;
    }
}
